package com.wisdom.system.service.impl.sys;


import com.github.pagehelper.Page;
import com.wisdom.system.dao.sys.SysDictItemMapper;
import com.wisdom.system.entity.base.PageRequest;
import com.wisdom.system.entity.base.PageResult;
import com.wisdom.system.entity.sys.SysDictItem;
import com.wisdom.system.common.annotation.ValidationUnique;
import com.wisdom.system.common.mybatis.PageUtil;
import com.wisdom.system.common.mybatis.SqlUtil;
import com.wisdom.system.service.sys.SysDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class SysDictItemServiceImpl implements SysDictItemService {

    @Autowired
    SysDictItemMapper sysDictItemMapper;

    @Override
    @ValidationUnique(key = {"code","fkDictCategoryCode"}, msg = {"编码已存在！"})
    public int addSysDictItemInfo(SysDictItem sysDictItem) {
        sysDictItem.setAddTime(new Date());
        return sysDictItemMapper.insert(sysDictItem);
    }

    @Override
    @ValidationUnique(key = {"code","fkDictCategoryCode"}, msg = {"编码已存在！"}, excludeSelf = true)
    public int updateSysDictItemInfo(SysDictItem sysDictItem) {
        return sysDictItemMapper.updateByPrimaryKeySelective(sysDictItem);
    }

    @Override
    public int delSysDictItemInfo(String id) {
        return sysDictItemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int delSysDictItemList(String ids) {
        String[] idArray = ids.split(",");
        Example example = new Example(SysDictItem.class);
        example.createCriteria().andIn("id", Arrays.asList(idArray));
        return sysDictItemMapper.deleteByExample(example);
    }

    @Override
    public SysDictItem getSysDictItemInfo(String id) {
        return sysDictItemMapper.getSysDictItemInfo(id);
    }

    @Override
    public List<SysDictItem> getSysDictItemList(String fkDictCategoryCode, String keyword) {
        Example example = new Example(SysDictItem.class);
        Example.Criteria  criteria = example.createCriteria();
        criteria.andEqualTo("fkDictCategoryCode", fkDictCategoryCode)
                .andLike("name", SqlUtil.likeEscapeH(keyword))
                .orLike("pyCode",SqlUtil.likeEscapeH(keyword))
                .orLike("wbCode",SqlUtil.likeEscapeH(keyword));
        example.orderBy("sort").asc().orderBy("addTime").desc();
        return sysDictItemMapper.selectByExample(example);
    }

    @Override
    public PageResult<SysDictItem> getSysDictItemPageList(String fkDictCategoryCode, String keyword, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getSysDictItemList(fkDictCategoryCode, keyword), page.getTotal());
    }

}



